package com.itcast.aspect;

import com.itcast.mapper.OperateLogMapper;
import com.itcast.pojo.OperateLog;
import com.itcast.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Slf4j
@Aspect
public class LogAspect {
    //request对象用于获取令牌
    @Autowired
    private HttpServletRequest request;
    //operatorLogMapper对象用于更新日志表
    @Autowired
    private OperateLogMapper operateLogMapper;

     /*//切入点
    @Pointcut("@annotation(com.itcast.annotation.Log)")
    private void pt(){}
    //通知
    @Around("pt()")*/

    //声明切面
    @Around("@annotation(com.itcast.annotation.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取请求头中的jwt令牌, 解析令牌
        String jwt = request.getHeader("token");
        //解析令牌中的载荷信息
        Claims claims = JwtUtils.parseJWT(jwt);
        //操作人ID - 当前登录员工ID
        Integer operateEmpId = (Integer) claims.get("id");
        //操作时间
        LocalDateTime operateTime = LocalDateTime.now();
        //操作类名
        String className = joinPoint.getTarget().getClass().getName();
        //操作方法名
        String methodName = joinPoint.getSignature().getName();
        //操作方法参数
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);
//        String params = Arrays.asList(joinPoint.getArgs()).toString();
        //记录方法开始时间
        long begin = System.currentTimeMillis();
        //调用原始目标方法运行
        Object result = joinPoint.proceed();
        //记录方法结束时间
        long end = System.currentTimeMillis();
        //方法返回值
        String returnValue = result.toString();
        //操作耗时
        Long costTime = end - begin;
        //记录操作日志
        OperateLog operateLog = new OperateLog(null, operateEmpId, operateTime, className, methodName, methodParams, returnValue, costTime,null);
        //将日志插入数据库中
        operateLogMapper.insert(operateLog);
        log.info("AOP记录操作日志: {}" , operateLog);
        //返回原始目标方法运行后的result
        return result;
    }
}
